{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2eb2d4d3-c44e-409c-88c2-d30f9ac2e716",
   "metadata": {},
   "source": [
    "### 导入依赖库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "eea83fb5-bd41-480e-962b-8c6c7df72b42",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_models import ChatZhipuAI\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.runnables import RunnableLambda\n",
    "from langchain_core.runnables import RunnableBranch\n",
    "from langchain_core.runnables.base import RunnableEach"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f38c7a38-1ab2-41e9-9c9d-80ae6ff8009c",
   "metadata": {},
   "source": [
    "### 配置API密钥¶"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8c961c52-7ba2-4521-81ca-82f8d8734eac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"ZHIPUAI_API_KEY\"] = \"你的api key\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4604e1fd-b59c-4459-b2e9-364a586e6de8",
   "metadata": {},
   "source": [
    "### 初始化GLM-4-Flash模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b267726f-b539-48db-a8c1-cda1f86f778b",
   "metadata": {},
   "outputs": [],
   "source": [
    "chat = ChatZhipuAI(\n",
    "    model=\"glm-4-flash\",\n",
    "    temperature=0.5,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43cd9773-50df-4cb9-9095-a81f046a6623",
   "metadata": {},
   "source": [
    "### Runnable接口与LCEL基础"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7f4c4ab6-26ed-40f5-b9d2-e5c3134e1d74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好，世界！\n"
     ]
    }
   ],
   "source": [
    "## 基础链式调用\n",
    "\n",
    "# 定义处理链 (LCEL语法)\n",
    "chain = (\n",
    "    RunnablePassthrough()  # 传递原始输入\n",
    "    | ChatPromptTemplate.from_template(\"将以下文本翻译成{language}：{text}\") \n",
    "    | chat  # GLM-4-Flash模型\n",
    "    | StrOutputParser()  # 提取文本内容\n",
    ")\n",
    "\n",
    "# 执行调用\n",
    "result = chain.invoke({\n",
    "    \"text\": \"Hello, world!\", \n",
    "    \"language\": \"中文\"\n",
    "})\n",
    "print(result)  # 输出：Bonjour le monde!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c8731435-a23b-4a7a-ad37-c6a0a8c2eac7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "根据您提供的麻婆豆腐菜谱，以下是所需的食材列表：\n",
      "\n",
      "1. 老豆腐\n",
      "2. 猪肉末\n",
      "3. 姜蒜末\n",
      "4. 葱花\n",
      "5. 豆瓣酱\n",
      "6. 花椒粉\n",
      "7. 食用油\n",
      "8. 生抽\n",
      "9. 老抽（可选）\n",
      "10. 料酒\n",
      "11. 水淀粉\n",
      "12. 鸡精或味精（可选）\n",
      "13. 清水\n",
      "14. 盐\n"
     ]
    }
   ],
   "source": [
    "##  多步骤组合链\n",
    "\n",
    "# 定义子链1：生成菜谱\n",
    "recipe_chain = (\n",
    "    ChatPromptTemplate.from_template(\"生成{cuisine}菜谱\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "# 定义子链2：生成购物清单\n",
    "shopping_chain = (\n",
    "    ChatPromptTemplate.from_template(\"根据菜谱列出食材：{recipe}\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "# 组合链\n",
    "full_chain = {\n",
    "    \"recipe\": recipe_chain,  # 先执行菜谱生成\n",
    "    \"cuisine\": RunnablePassthrough()  # 传递原始输入\n",
    "} | shopping_chain  # 将菜谱结果传递给购物清单链\n",
    "\n",
    "result = full_chain.invoke(\"川菜\")\n",
    "print(result)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbd465fd-52a6-4b6d-9350-d584bea6e999",
   "metadata": {},
   "source": [
    "### 异步处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8a94647d-a92b-4ff7-9ccf-d4634c8ffb04",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "机器学习就像是一个聪明的学生，他不需要老师反复讲解，只要给他一些例子，他就能自己学会如何解决问题。这个过程就像是一个孩子通过观察和模仿来学习说话和走路。在这个比喻中，例子就是“数据”，而学生就是“算法”。算法通过不断分析这些数据，就像孩子通过不断模仿来学习语言和动作一样，最终能够独立地识别模式和做出决策。\n"
     ]
    }
   ],
   "source": [
    "## 基础异步调用\n",
    "import asyncio\n",
    "\n",
    "async def async_query():\n",
    "    chain = (\n",
    "        ChatPromptTemplate.from_template(\"用比喻解释{concept}\")\n",
    "        | chat\n",
    "        | StrOutputParser()\n",
    "    )\n",
    "    return await chain.ainvoke({\"concept\": \"机器学习\"})\n",
    "\n",
    "# 运行异步任务\n",
    "# result = asyncio.run(async_query())\n",
    "# 在 Jupyter 单元格中直接使用 await\n",
    "result = await async_query()\n",
    "print(result)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ab4cb299-daae-4ad3-9ee4-863c691188db",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1. \"人工智能：未来科技浪潮中的引领者\"\\n2. \"智能革命：人工智能如何改变我们的世界\"\\n3. \"从科幻走向现实：人工智能的无限可能\"\\n4. \"AI赋能未来：探索人工智能的无限边界\"\\n5. \"智能时代来临：人工智能如何重塑产业格局\"\\n6. \"人工智能：开启智慧生活新篇章\"\\n7. \"智能进化论：人工智能技术发展历程解析\"\\n8. \"AI赋能教育：人工智能如何助力人才培养\"\\n9. \"人工智能：推动医疗健康产业变革的力量\"\\n10. \"智能时代，人工智能如何助力社会治理创新\"', '1. \"全球气候变暖：挑战与应对之道\"\\n2. \"极端天气频发，气候变化警钟长鸣\"\\n3. \"绿色未来：携手应对气候变化危机\"\\n4. \"气候变化下的生态危机：我们能做什么？\"\\n5. \"低碳生活，共建地球家园——应对气候变化行动指南\"\\n6. \"气候变化对农业的影响：挑战与转型之路\"\\n7. \"从巴黎协定到行动：全球气候治理的挑战与机遇\"\\n8. \"城市如何应对气候变化：可持续发展的绿色策略\"\\n9. \"气候变化与人类健康：揭示未知风险与应对策略\"\\n10. \"绿色能源革命：推动全球气候治理新格局\"']\n"
     ]
    }
   ],
   "source": [
    "## 批量异步处理\n",
    "async def batch_process():\n",
    "    chain = (\n",
    "        ChatPromptTemplate.from_template(\"生成关于{theme}的标题\")\n",
    "        | chat\n",
    "        | StrOutputParser()\n",
    "    )\n",
    "    \n",
    "    # 并行处理多个请求\n",
    "    tasks = [\n",
    "        chain.ainvoke({\"theme\": \"人工智能\"}),\n",
    "        chain.ainvoke({\"theme\": \"气候变化\"})\n",
    "    ]\n",
    "    return await asyncio.gather(*tasks)\n",
    "\n",
    "# 执行批量任务\n",
    "# results = asyncio.run(batch_process())\n",
    "results = await batch_process()\n",
    "print(results)  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0aa9223a-51a3-4f9e-be3c-66d7e0f90d80",
   "metadata": {},
   "source": [
    "### 流式处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b08c5a4c-3e33-4443-a6da-0e5be060e5d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "人工智能是计算机科学领域，研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统。它通过算法和机器学习，使计算机具备学习、推理、感知和决策能力，广泛应用于各行各业。"
     ]
    }
   ],
   "source": [
    "## 基础流式输出\n",
    "# 流式响应处理\n",
    "chain = (\n",
    "    ChatPromptTemplate.from_template(\"用100字介绍{topic}\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "for chunk in chain.stream({\"topic\": \"人工智能\"}):\n",
    "    print(chunk, end=\"\", flush=True) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "4d71ed01-e438-4b1e-a50d-d5a0be538c47",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前字数：61\n",
      "\n"
     ]
    }
   ],
   "source": [
    "## 带中间状态的流式处理\n",
    "\n",
    "\n",
    "# 自定义流处理器\n",
    "def word_counter(input_text):\n",
    "    word_count = len(input_text.split())\n",
    "    yield f\"当前字数：{word_count}\\n\"\n",
    "\n",
    "# 构建流式分析链\n",
    "analysis_chain = (\n",
    "    ChatPromptTemplate.from_template(\"分析{AI_tool}的市场竞争力\")\n",
    "    | chat\n",
    "    | StrOutputParser() \n",
    "    | RunnableLambda(word_counter)  # 添加自定义处理\n",
    ")\n",
    "\n",
    "for chunk in analysis_chain.stream({\"AI_tool\": \"deepseek\"}):\n",
    "    print(chunk)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2ad450f-c959-4504-bd12-c042209ff424",
   "metadata": {},
   "source": [
    "### 复杂逻辑编排"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b431bc33-f875-40d3-96da-d25e123061fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "为什么人工智能不喜欢去健身房？\n",
      "\n",
      "因为它只想“训练数据”，而不是“锻炼身体”！😄\n",
      "【科技新闻简讯】\n",
      "我国科学家成功研发新型太阳能电池，效率提升30%\n",
      "\n",
      "近日，我国科研团队在太阳能电池领域取得重大突破，成功研发出一种新型太阳能电池。该电池采用新型材料，通过优化设计，将光电转换效率提升至30%，创下了国际领先水平。据悉，该技术有望广泛应用于光伏发电、太阳能充电等领域，为我国新能源产业发展提供有力支持。目前，该成果已申请国际专利，并计划在未来五年内实现产业化应用。\n"
     ]
    }
   ],
   "source": [
    "## 条件分支路由\n",
    "\n",
    "\n",
    "# 定义分类器\n",
    "def classify_input(text: str) -> str:\n",
    "    if \"笑话\" in text:\n",
    "        return \"joke\"\n",
    "    elif \"新闻\" in text:\n",
    "        return \"news\"\n",
    "    return \"other\"\n",
    "\n",
    "# 定义子链\n",
    "joke_chain = (\n",
    "    ChatPromptTemplate.from_template(\"生成关于{topic}的笑话\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "news_chain = (\n",
    "    ChatPromptTemplate.from_template(\"写一则关于{topic}的简讯\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "default_chain = (\n",
    "    ChatPromptTemplate.from_template(\"回答关于{topic}的问题\")\n",
    "    | chat\n",
    "    | StrOutputParser()\n",
    ")\n",
    "\n",
    "# 构建分支逻辑\n",
    "branch = RunnableBranch(\n",
    "    (lambda x: classify_input(x[\"topic\"]) == \"joke\", joke_chain),\n",
    "    (lambda x: classify_input(x[\"topic\"]) == \"news\", news_chain),\n",
    "    default_chain\n",
    ")\n",
    "\n",
    "# 测试分支\n",
    "print(branch.invoke({\"topic\": \"人工智能笑话\"}))  # 输出笑话\n",
    "print(branch.invoke({\"topic\": \"科技新闻\"}))     # 输出简讯"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ff7d0cbd-4b51-4f1d-adc4-0f6c57370e05",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['人工智能（Artificial Intelligence，简称AI）是指由人制造出来的系统所表现出的智能行为。这种智能可以是机器学习、自然语言处理、视觉识别、决策制定、问题解决等多种形式。人工智能的目标是使计算机能够执行通常需要人类智能才能完成的任务。\\n\\n以下是人工智能的一些关键特点：\\n\\n1. **机器学习**：通过算法从数据中学习并改进性能。\\n2. **自然语言处理**：让机器能够理解和生成人类语言。\\n3. **计算机视觉**：让机器能够“看到”和理解图像或视频。\\n4. **机器人技术**：将人工智能集成到物理机器人中。\\n5. **专家系统**：模拟人类专家解决问题的能力。\\n\\n人工智能的应用领域非常广泛，包括但不限于以下方面：\\n\\n- **医疗**：辅助诊断、药物研发等。\\n- **交通**：自动驾驶、交通流量管理等。\\n- **金融**：风险评估、欺诈检测等。\\n- **教育**：个性化学习、自动评分等。\\n- **娱乐**：游戏、虚拟助手等。\\n\\n人工智能的发展对人类社会具有深远的影响，但也带来了一些伦理和安全方面的挑战。因此，在推动人工智能发展的同时，也需要关注其潜在的风险和影响，并采取措施确保其健康、可持续发展。', '机器学习是人工智能（AI）的一个分支，它使计算机系统能够从数据中学习并做出决策或预测，而无需显式编程。简单来说，机器学习就是让计算机通过经验改进其性能的过程。\\n\\n以下是机器学习的一些关键点：\\n\\n1. **数据驱动**：机器学习依赖于大量数据来训练模型。这些数据可以是结构化的（如数据库中的表格）或非结构化的（如图像、文本、音频和视频）。\\n\\n2. **算法**：机器学习使用各种算法来分析数据并从中学习。这些算法可以是监督学习、无监督学习或强化学习。\\n\\n3. **监督学习**：在这种方法中，模型从标记的数据（即已知结果）中学习。例如，通过学习大量已标记的电子邮件，模型可以学会将新电子邮件分类为垃圾邮件或非垃圾邮件。\\n\\n4. **无监督学习**：在这种方法中，模型从未标记的数据中学习。例如，无监督学习可以用于发现客户购买模式或市场趋势。\\n\\n5. **强化学习**：在这种方法中，模型通过与环境的交互来学习。它通过尝试不同的行动并从中学习来优化其行为。\\n\\n6. **应用**：机器学习在各个领域都有广泛的应用，包括自然语言处理、图像识别、推荐系统、医疗诊断、自动驾驶汽车等。\\n\\n7. **挑战**：尽管机器学习有许多优势，但也面临一些挑战，如数据隐私、偏见、可解释性和伦理问题。\\n\\n总之，机器学习是一种强大的技术，它使计算机能够从数据中学习，并在此过程中不断提高其性能。', '深度学习是机器学习的一个子领域，主要研究的是如何使用神经网络来模拟人脑处理信息的方式，以实现对数据的自动学习和提取特征。它通过构建具有多层节点的神经网络模型，使得模型能够自动从原始数据中学习到更深层次的特征表示。\\n\\n以下是深度学习的一些关键点：\\n\\n1. **神经网络**：深度学习的基础是神经网络，特别是深度神经网络（DNN）。神经网络由多个层组成，包括输入层、隐藏层和输出层。\\n\\n2. **多层结构**：与传统的单层神经网络相比，深度神经网络包含多个隐藏层，这使得模型能够学习更复杂的特征和模式。\\n\\n3. **自动特征提取**：深度学习模型可以自动从原始数据中提取特征，无需人工干预。这使得深度学习在图像识别、语音识别等领域具有显著优势。\\n\\n4. **大规模数据**：深度学习通常需要大量的数据进行训练，以使模型能够学习到有效的特征表示。\\n\\n5. **优化算法**：深度学习模型通常使用梯度下降等优化算法进行训练，以最小化预测误差。\\n\\n6. **应用领域**：深度学习在多个领域取得了显著成果，包括图像识别、语音识别、自然语言处理、推荐系统等。\\n\\n深度学习在近年来取得了巨大进展，推动了人工智能技术的发展。随着计算能力的提升和数据量的增加，深度学习有望在更多领域发挥重要作用。']\n"
     ]
    }
   ],
   "source": [
    "## 循环处理\n",
    "\n",
    "# 设置模板提示词\n",
    "prompt = ChatPromptTemplate.from_template(\"什么是{topic}\")\n",
    "# 指定模型\n",
    "model = chat\n",
    "# 设置输出内容\n",
    "output_parser = StrOutputParser()\n",
    "# 构建工作链\n",
    "chain = prompt | model | output_parser\n",
    "\n",
    "# 构建循环链\n",
    "loop_chain = RunnableEach(bound=chain)\n",
    "\n",
    "# 启动循环\n",
    "response = loop_chain.invoke([{'topic':'人工智能'},\n",
    "                            {'topic':'机器学习'},\n",
    "                            {'topic':'深度学习'}])\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34d126de-c245-4e64-960d-91e472c17696",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
